package com.lzp.customview.togglebtn

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.core.view.ViewCompat
import androidx.customview.widget.ViewDragHelper
import com.lzp.customview.R
import com.utils.SizeUtils

/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 2020/7/22
 */
class SeekBar : FrameLayout {

    private val dp1 = SizeUtils.dip2px(context, 1)

    private var viewWidth = 0
    private var viewHeight = 0

    //进度条部分
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)
    private var progressColor = Color.parseColor("#ff2c2d2e")
    private val progressLineHeight = dp1 * 2

    //进度条的宽度
    private var progressWidth = 0f

    //切换的图片
    private val toggleIcon = ImageView(context)
    private val toggleIconWidth = dp1 * 44
    private var toggleImageRes = R.mipmap.pic_knob


    private val dragHelper: ViewDragHelper = ViewDragHelper.create(this, DragHelperCallBack())

    //当前的进度：百分数比如：60%，此值为60
    private var progrss = 0f

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        toggleIcon.setImageResource(toggleImageRes)
    }

    init {
        progressPaint.style = Paint.Style.FILL
        progressPaint.color = progressColor
        progressPaint.strokeWidth = progressLineHeight.toFloat()
        progressPaint.style = Paint.Style.STROKE
        progressPaint.strokeCap = Paint.Cap.ROUND

        toggleIcon.layoutParams = LayoutParams(toggleIconWidth, ViewGroup.LayoutParams.MATCH_PARENT)
        toggleIcon.scaleType = ImageView.ScaleType.CENTER_INSIDE
        addView(toggleIcon)
    }


    inner class DragHelperCallBack : ViewDragHelper.Callback() {
        override fun tryCaptureView(child: View, pointerId: Int): Boolean {
            return child == toggleIcon
        }

        override fun clampViewPositionHorizontal(child: View, left: Int, dx: Int): Int {
            var tempLeft = left
            if (left < 0) {
                tempLeft = 0
            } else if (left > width - toggleIconWidth) {
                tempLeft = width - toggleIconWidth
            }
            progrss = tempLeft / progressWidth
            progressChangedListener?.onProgressChange(progrss)
            return tempLeft
        }

        override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
            //停止滚动之后
        }
    }


    override fun computeScroll() {
        //回弹时刷新界面
        if (dragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(this)
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (w != 0 && h != 0) {
            viewWidth = w
            viewHeight = h
            progressWidth = viewWidth - toggleIconWidth.toFloat()
        }
    }

    override fun dispatchDraw(canvas: Canvas?) {
        //画背景点
        drawLine(canvas)
        super.dispatchDraw(canvas)

    }

    private fun drawLine(canvas: Canvas?) {
        if (canvas == null) {
            return
        }
        //划线
        canvas.drawLine(toggleIconWidth / 2f, height / 2f, viewWidth - toggleIconWidth / 2f, height / 2f, progressPaint)
    }

    fun setToggleImageRes(imgRes: Int) {
        toggleIcon.setImageResource(imgRes)
    }

    fun setProgress(progress: Float) {
        this.progrss = progrss
        post {
            dragHelper.smoothSlideViewTo(toggleIcon, (progressWidth * progress / 100f).toInt(), 0)
            ViewCompat.postInvalidateOnAnimation(this@SeekBar)
        }
    }

    fun getProgress(): Float {
        return progrss
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return if (ev != null) {
            dragHelper.shouldInterceptTouchEvent(ev)
        } else {
            super.onInterceptTouchEvent(ev)
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let {
            val action = it.action
            when (action) {
                MotionEvent.ACTION_DOWN -> {
                    var x = it.x - toggleIconWidth / 2
                    if (it.x < 0) {
                        x = 0f
                    } else if (it.x > width - toggleIconWidth) {
                        x = width - toggleIconWidth.toFloat()
                    }
                    dragHelper.smoothSlideViewTo(toggleIcon, x.toInt(), 0)
                    ViewCompat.postInvalidateOnAnimation(this@SeekBar)
                    progressChangedListener?.onProgressChange(x / progressWidth * 100f)
                }
            }
            dragHelper.processTouchEvent(event)
            return true
        }
        return super.onTouchEvent(event)
    }

    /************以下为设置监听************/
    private var progressChangedListener: OnProgressChangedListener? = null
    fun setOnProgressChangedListener(progressChangedListener: OnProgressChangedListener?) {
        this.progressChangedListener = progressChangedListener
    }

    interface OnProgressChangedListener {
        fun onProgressChange(progress: Float)
    }
}